import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 6000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    } else if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    } else if (error.response.status === 500) {
      notification.error({
        message: '系统提示',
        description: data.msg || '系统错误，请稍后再试'
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  // 业务正常报错
  if (response.data.code !== 200) {
    notification.error({
      message: '系统提示',
      description: response.data.msg || '系统错误，请稍后再试'
    })
    return Promise.reject(response.data.msg)
  }
  // 服务端处理，自动续期 替换新的 token
  if (response.headers['Access-Token']) {
    Vue.ls.set(ACCESS_TOKEN, response.headers['Access-Token'], 7 * 24 * 60 * 60 * 1000 - 2 * 1000)
  }
  return response.data
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, {
      post (url, params = {}) {
        return service.post(url, params, {
          transformRequest: [(params) => {
            return qs.stringify(params)
          }],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
      },
      put (url, params = {}) {
        return service.put(url, params, {
          transformRequest: [(params) => {
            /* let result = ''
            Object.keys(params).forEach((key) => {
              if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
                result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
              }
            })
            if (result.length > 0) {
              result = result.substr(0, result.length - 1)
            }
            return result */
            return qs.stringify(params)
          }],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
      },
      get (url, params = {}) {
        return service.get(url, params)
      },
      delete (url, params = {}) {
        return service.delete(url, { data: params })
      },
      export () {},
      download () {},
      upload () {}
    })
  }
}

export {
  installer as VueAxios,
  service as axios
}
